//package com.atung.parking.config.payUtil;
//
//import com.alibaba.fastjson.JSONObject;
//import com.atung.parking.dto.CreateOrderEntity;
//import com.wechat.pay.java.core.RSAAutoCertificateConfig;
//import com.wechat.pay.java.core.exception.HttpException;
//import com.wechat.pay.java.core.exception.MalformedMessageException;
//import com.wechat.pay.java.core.exception.ServiceException;
//import com.wechat.pay.java.core.notification.NotificationParser;
//import com.wechat.pay.java.core.notification.RequestParam;
//import com.wechat.pay.java.service.partnerpayments.app.model.Transaction;
//import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
//import com.wechat.pay.java.service.payments.jsapi.model.Amount;
//import com.wechat.pay.java.service.payments.jsapi.model.Payer;
//import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
//import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
//import com.wechat.pay.java.service.refund.RefundService;
//import com.wechat.pay.java.service.refund.model.AmountReq;
//import com.wechat.pay.java.service.refund.model.CreateRequest;
//import com.wechat.pay.java.service.refund.model.Refund;
//import com.wechat.pay.java.service.refund.model.Status;
//import lombok.extern.log4j.Log4j2;
//import org.springframework.stereotype.Service;
//import org.springframework.util.StringUtils;
//
//import javax.annotation.Resource;
//import javax.servlet.http.HttpServletRequest;
//import java.util.HashMap;
//import java.util.LinkedHashMap;
//import java.util.Map;
//
///**
// * @author Administrator
// */
//@Service
//@Log4j2
//public class WxPayService {
//
//    @Resource
//    private RSAAutoCertificateConfig rsaAutoCertificateConfig;
//
//    /***
//     * 预支付订单
//     * @param
//     * @return
//     */
//    public Map createOrder(CreateOrderEntity createOrder) throws Exception {
//        String orderNo = createOrder.getOutTradeNo();
//        Integer totalFee = 100;
//        //创建初始化订单
//        //todo,创建订单这边你们自己来（后面我会放出表结构）
//        //请求微信支付相关配置
//        JsapiServiceExtension service =
//                new JsapiServiceExtension.Builder()
//                        .config(rsaAutoCertificateConfig)
//                        .signType("RSA") // 不填默认为RSA
//                        .build();
//        PrepayWithRequestPaymentResponse response = new PrepayWithRequestPaymentResponse();
//        try {
//            PrepayRequest request = new PrepayRequest();
//            request.setAppid(WxPayConfig.appId);
//            request.setMchid(WxPayConfig.merchantId);
//            request.setDescription("");
//            request.setOutTradeNo(orderNo);
//            request.setNotifyUrl(WxPayConfig.payNotifyUrl);
//            Amount amount = new Amount();
//            amount.setTotal(totalFee);
//            request.setAmount(amount);
//            Payer payer = new Payer();
//            payer.setOpenid(createOrder.getWxOpenId());
//            request.setPayer(payer);
//            log.info("请求预支付下单，请求参数：{}", JSONObject.toJSONString(request));
//            // 调用预下单接口
//            response = service.prepayWithRequestPayment(request);
//            log.info("订单【{}】发起预支付成功，返回信息：{}", orderNo, response);
//        } catch (HttpException e) { // 发送HTTP请求失败
//            log.error("微信下单发送HTTP请求失败，错误信息：{}", e.getHttpRequest());
////            return R.error("下单失败");
//        } catch (ServiceException e) { // 服务返回状态小于200或大于等于300，例如500
//            log.error("微信下单服务状态错误，错误信息：{}", e.getErrorMessage());
////            return R.error("下单失败");
//        } catch (MalformedMessageException e) { // 服务返回成功，返回体类型不合法，或者解析返回体失败
//            log.error("服务返回成功，返回体类型不合法，或者解析返回体失败，错误信息：{}", e.getMessage());
////            return R.error("下单失败");
//        }
//
//        System.out.println(response);
//        return null;
//    }
//
//    public synchronized String payNotify(HttpServletRequest request) throws Exception {
//        String signature = request.getHeader("Wechatpay-Signature");
//        // 请求头Wechatpay-nonce
//        String nonce = request.getHeader("Wechatpay-Nonce");
//        // 请求头Wechatpay-Timestamp
//        String timestamp = request.getHeader("Wechatpay-Timestamp");
//        // 微信支付证书序列号
//        String serial = request.getHeader("Wechatpay-Serial");
//        // 签名方式
//        String signType = request.getHeader("Wechatpay-Signature-Type");
//        RequestParam requestParam = new RequestParam.Builder()
//                .serialNumber(serial)
//                .nonce(nonce)
//                .signature(signature)
//                .timestamp(timestamp)
//                .signType(signType)
//                .body(HttpServletUtils.getRequestBody(request))
//                .build();
//        NotificationParser parser = new NotificationParser(rsaAutoCertificateConfig);
//        log.info("验签参数：{}", requestParam);
//        Transaction transaction = parser.parse(requestParam, Transaction.class);
//        String outTradeNo = transaction.getOutTradeNo();
//        log.info("验签成功！-支付回调结果：{}", transaction.toString());
////        transaction.getOutTradeNo()
//        Map<String, String> returnMap = new HashMap<>(2);
//        returnMap.put("code", "FAIL");
//        returnMap.put("message", "失败");
//        returnMap.put("code", "SUCCESS");
//        returnMap.put("message", "成功");
//        return JSONObject.toJSONString(returnMap);
//    }
//
//    /***
//     * 微信申请退款
//     * @param outTradeNo 商户订单号
//     * @param totalAmount 退款金额，单位分
//     * @return
//     */
//    public void createRefund(String outTradeNo, Long totalAmount, String outRefundNo) {
//        log.info("申请退款参数，outTradeNo：{}，totalAmount：{}，outRefundNo：{}", outTradeNo, totalAmount, outRefundNo);
//        //返回参数
//        LinkedHashMap map = new LinkedHashMap();
//        map.put("out_trade_no", outTradeNo);
//        map.put("success", false);
//        map.put("msg", "退款失败！");
//        if (StringUtils.isEmpty(outRefundNo)) {
//            outRefundNo = "REFUND_" + outTradeNo;
//        }
//        map.put("out_refund_no", outRefundNo);
//        //申请退款订单，需要变更订单记录
//        try {
//            // 构建退款service
//            RefundService service = new RefundService.Builder()
//                    .config(rsaAutoCertificateConfig)
//                    .build();
//            CreateRequest request = new CreateRequest();
//            // 调用request.setXxx(val)设置所需参数，具体参数可见Request定义
//            request.setOutTradeNo(outTradeNo);
//            request.setOutRefundNo(outRefundNo);
//            AmountReq amount = new AmountReq();
////            amount.setTotal();
//            amount.setRefund(totalAmount);
//            amount.setCurrency("CNY");
//            request.setAmount(amount);
//            request.setNotifyUrl(WxPayConfig.refundNotifyUrl);
//            //接收退款返回参数
//            Refund refund = service.create(request);
//            log.info("退款返回信息：{}", refund);
//            //SUCCESS:退款成功，PROCESSING：正在处理中
//            if (refund.getStatus().equals(Status.SUCCESS)) {
//                map.put("success", true);
//                map.put("msg", "退款成功！");
//                map.put("transaction_id", refund.getTransactionId());
//                //说明退款成功，开始接下来的业务操作
//                //主动查询
//            } else if (refund.getStatus().equals(Status.ABNORMAL)) {
//                map.put("success", false);
//                map.put("msg", "退款失败，账户异常！");
//                map.put("transaction_id", refund.getTransactionId());
//            } else if (refund.getStatus().equals(Status.PROCESSING)) {
//                map.put("success", true);
//                map.put("msg", "正在退款中！");
//                map.put("transaction_id", refund.getTransactionId());
//            } else if (refund.getStatus().equals(Status.CLOSED)) {
//                map.put("success", false);
//                map.put("msg", "用户余额不足或者订单超过退款期限！");
//                map.put("transaction_id", refund.getTransactionId());
//            }
//        } catch (ServiceException e) {
//            log.error("退款失败！，错误信息：{}", e.getErrorMessage());
//        } catch (Exception e) {
//            log.error("服务返回成功，返回体类型不合法，或者解析返回体失败，错误信息：{}", e.getMessage());
//        }
//        log.info("微信退款响应参数：{}", map);
//    }
//}